package compound.repository

import compound.repository.entries.Compound

/**
 * this controller is used to discover chemical compounds in the given parameter
 */
class DiscoveryController {

  //injected service
  DiscoveryService discoveryService
  DataExportService dataExportService = new DataExportService();

  def index = {

    if (session.getAttribute("query") != null) {
      return [query: session.getAttribute("query").toString()]
    }

    return

  }
  /**
   * process a query and returns a map containning all the found chemical names
   */
  def process = {

    //logger is added automatically by grails
    log.debug "executing a query..."

    String query = ""

    if (params.query != null) {
      query = params.query
      session.setAttribute("query", query);
    }
    else {
      query = session.getAttribute("query").toString()
    }


    if (query == null || query.trim().length() == 0) {
      flash.message = "Error! Query parameter is mandatory, Please Enter Query."
      redirect(action: "index")
    }

    //params are added automatically by grails
    assert (query != null)

    def limitConfidence = 0.5

    //if we don't have a confidence limit set we use the default
    //otherwise we assign on
    if (params.limitConfidence != null) {
      limitConfidence = params.limitConfidence
    }

    log.debug "params.query ::: " + query

    //contains the final result
    Collection<Map<Compound, ?>> result = discoveryService.process(query, limitConfidence)

    assert result != null, "discovery service returned null, which can't be. Please fill a bug report!"


    if (params?.format && params.format != "html") //Export
    {
      dataExportService.exportDiscover(result, response, params)
    } else {
      //forward to the controller
      return [result: result]
    }

  }


  def show_help_remote = {
    render """

             <div class="message">

                Please enter your content into the text field. An example would be:
                <br>
                <br>
                Hello benzene world, you are full of vitamin a
                <br>
                <br>
                we also support the following identifiers, besides synonyms.
                <br>
                <br>

                <ul>
                  <li>KEGG</li>
                  <li>CAS</li>
                  <li>LipidMAPS</li>
                  <li>Std Inchi Code</li>
                  <li>Std Inchi Key</li>
                </ul>

                <br>
                Please be aware that the discovery based on synonyms is not perfect and can lead to false positives.
             
             </div>"""
  }

}